<template>
  <div>
    <div id="baidu-map"  ref="mapRef" style="width:100%; height:300px;"></div>
  </div>
</template>

<script>
export default {
  name: 'BaiduMap',
  data() {
    return {
      map: null,
      geoc: null,
      selectedPoint: null,
      selectedAddress: '',
      marker: null
    };
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      this.map = new BMap.Map('baidu-map');
      const point = new BMap.Point(116.404, 39.915);
      this.map.centerAndZoom(point, 15);
      this.map.enableScrollWheelZoom(true);
      this.geoc = new BMap.Geocoder();
      this.map.addEventListener('click', (e) => {
        this.selectedPoint = e.point;
        this.addMarker(e.point);
        this.getAddress(e.point);
      });
    },
    getAddress(point) {
      this.geoc.getLocation(point, (result) => {
        if (result) {
          this.selectedAddress = result.address;
          this.$emit('address-selected', this.selectedAddress); // 发送自定义事件，将selectedAddress的值传递出去
        } else {
          this.selectedAddress = '获取地址失败';
        }
      });
    },
    addMarker(point) {
      if (this.marker) {
        this.map.removeOverlay(this.marker);
      }
      this.marker = new BMap.Marker(point);
      this.map.addOverlay(this.marker);
    },
  },
};
</script>
